'use strict';

/**
 * @description: 过滤筛选树 -- search tree
 * @param treeData 数据源
 * @param findStr 关键字
 * @param label 关键字段
 * @return new tree data
 */
const fuzzySearchTree = (treeData, findStr, label = "title") => {
    if (!treeData)
        return [];
    let list = [];
    treeData.forEach((item) => {
        // 确保label属性是字符串并且包含findStr
        if (typeof item[label] === "string" && item[label].includes(findStr)) {
            // 递归处理子节点
            let children = item.children ? fuzzySearchTree(item.children, findStr, label) : [];
            // 如果子节点中没有匹配的项，则保留原子节点
            children = children.length > 0 ? children : item.children;
            // 构造新的节点，保留匹配的子节点
            const obj = { ...item, children };
            list.push(obj);
        }
        else if (item.children && item.children.length > 0) {
            // 如果当前节点不匹配，但有子节点，则递归处理子节点
            const children = fuzzySearchTree(item.children, findStr, label);
            // 如果子节点中有匹配的项，则保留当前节点，并更新其子节点
            if (children.length > 0) {
                const obj = { ...item, children };
                list.push(obj);
            }
        }
    });
    return list;
};

exports.fuzzySearchTree = fuzzySearchTree;
